<template>
  <el-form-item label="输入文件" prop="inputFile">
    <el-upload
      v-model:file-list="uploadForm.fileList"
      accept=".xls,.xlsx"
      :auto-upload="false"
      :limit="1"
      class="upload-demo"
      show-file-list
      @change="onChange"
      @before-remove="onBeforeRemove"
      @exceed="onExceed"
    >
      <template #trigger>
        <el-button type="danger" plain>选择</el-button>
      </template>
      <template #tip>
        <div class="el-upload__tip">请上传Excel文件</div>
      </template>
      <el-button size="small" type="text" @click="showDialog = true">示例文件</el-button>
    </el-upload>
    <el-dialog
      v-model="showDialog"
      title="示例文件"
      width="50%"
      top="5vh"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <ExcelRender :src="exampleXlsx" />
      <template #footer>
        <el-button type="primary" @click="uploadExample">上传</el-button>
        <el-button @click="showDialog = false">取消</el-button>
      </template>
    </el-dialog>
  </el-form-item>
</template>

<script setup>
import { reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ExcelRender from '@/components/Renderers/ExcelRender.vue'

// 接收 props
const props = defineProps({
  fileList: Array,
  exampleXlsx: String,
  submitted: Boolean,
  maxFileSize: Number
})
const emit = defineEmits(['update:fileList'])

// 本地 reactive 表单数据
const uploadForm = reactive({
  fileList: props.fileList || []
})
const showDialog = ref(false)

// 方法：校验文件
function validateExcel(raw) {
  const isExcel = ['application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].includes(raw.type)
  if (!isExcel) {
    ElMessage.error('只能上传 Excel (.xls/.xlsx) 文件')
    return false
  }
  if (raw.size > props.maxFileSize) {
    const sizeMB = (raw.size / 1024 / 1024).toFixed(2)
    ElMessage.error(`文件 (${sizeMB}MB)，超出 ${props.maxFileSize/1024/1024}MB`)
    return false
  }
  return true
}

// 处理上传变化
function onChange({ raw }) {
  if (!validateExcel(raw)) {
    uploadForm.fileList = []
  } else {
    uploadForm.fileList = [{ raw, name: raw.name }]
  }
  emit('update:fileList', uploadForm.fileList)
}

function onExceed(files) {
  ElMessage.warning(`最多上传1个文件，本次选择${files.length}个`)
}

function onBeforeRemove(file) {
  return ElMessageBox.confirm(`取消上传 ${file.name} ?`)
    .then(() => true)
    .catch(() => false)
}

// 上传示例文件
async function uploadExample() {
  try {
    const resp = await fetch(props.exampleXlsx)
    const blob = await resp.blob()
    const file = new File([blob], '示例文件.xlsx', { type: blob.type })
    uploadForm.fileList = [{ raw: file, name: file.name }]
    emit('update:fileList', uploadForm.fileList)
    showDialog.value = false
  } catch {
    ElMessage.error('上传示例失败')
  }
}
</script>

<style scoped>
.upload-demo {
  display: block;
}
</style>
